package db

import (
	"errors"
	"gorm.io/gorm"
	"hr/api/dto"
)

type UserManage struct {
	AppModel
	Avatar   string `gorm:"size:255" json:"avatar"`
	OpenId   string `gorm:"size:255" json:"open_id"`
	Name     string `gorm:"size:64" json:"name"`
	Sex      string `gorm:"size:64" json:"sex"`
	Phone    string `gorm:"size:64" json:"phone"`
	CreateBy string `gorm:"size:128" json:"createBy"` // 创建人
	UpdateBy string `gorm:"size:128" json:"updateBy"` // 更新人
	Remark   string `gorm:"size:255" json:"remark"`   //备注
	Status   string `gorm:"size:64;" json:"status"`
}

func (m *UserManage) TableName() string {
	return "user_manage"
}

type UserManagePageModel struct {
	Total    int64        `json:"total"`
	Result   []UserManage `json:"result"`
	PageNo   int          `json:"pageNo"`
	PageSize int          `json:"pageSize"`
}

func GetUserManagePaging(pagination dto.Pagination, name string) (UserManagePageModel, error) {
	result := UserManagePageModel{
		Total:    0,
		Result:   make([]UserManage, 0),
		PageNo:   pagination.PageNo,
		PageSize: pagination.PageSize,
	}
	offset := (pagination.PageNo - 1) * pagination.PageSize
	dbs := GetInstance().Model(&UserManage{})
	if name != "" {
		dbs = dbs.Where("phone LIKE ?", "%"+name+"%")
	}

	dbs = dbs.Order("created_at desc")

	if err := dbs.Offset(offset).Limit(pagination.PageSize).Find(&result.Result).Error; err != nil {
		return result, err
	}
	if err := dbs.Offset(-1).Limit(-1).Count(&result.Total).Error; err != nil {
		return result, err
	}
	return result, nil
}

// GetUserManage 根据条件查找
func GetUserManage(p map[string]interface{}) (UserManage, error, string) {
	f := UserManage{}
	err := GetInstance().Where(p).First(&f).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return f, errors.New("查无记录"), "0"
		}
		return f, errors.New(err.Error()), "1"
	}
	return f, nil, "2"
}

func CreateUserManage(p dto.UserManageRequest, user string) (UserManage, error) {
	d := UserManage{
		Avatar:   p.Avatar,
		OpenId:   p.OpenId,
		Name:     p.Name,
		Sex:      p.Sex,
		Phone:    p.Phone,
		CreateBy: user,
		Status:   p.Status,
	}
	if err := GetInstance().Create(&d).Error; err != nil {
		return d, err
	}
	return d, nil
}

func UpdateUserManage(id uint, p dto.UserManageRequest, userId string) (UserManage, error) {
	f := UserManage{
		AppModel: AppModel{
			ID: id,
		},
	}
	err := GetInstance().Model(&f).Updates(UserManage{
		Avatar:   p.Avatar,
		OpenId:   p.OpenId,
		Name:     p.Name,
		Sex:      p.Sex,
		Phone:    p.Phone,
		UpdateBy: userId,
		Status:   p.Status,
	}).Updates(map[string]interface{}{
		"id": id,
	}).Scan(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}

func DeleteUserManage(id uint) (UserManage, error) {
	f := UserManage{}
	err := GetInstance().Unscoped().Where("id = ?", id).Delete(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}
